/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.e2e.haiti.infrastructure.surveyor;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;



/**
 * Demonstrates combining a TabHost with a ViewPager to implement a tab UI
 * that switches between tabs and also allows the user to perform horizontal
 * flicks to move between the tabs.
 */
public class Questionnaire extends SherlockFragmentActivity {
	
    public static Utils utilsHelper = null;
    public static Cursor structureCursor = null;
    public static int structureID;
    
    private static final int DEMOGRAPHICS_TAB = 0;
    private static final int LAYOUT_TAB = 1;
    private static final int PRIMARY_SYSTEM_TAB = 2;

    private static final int STRUCTURE_NOTE_DIALOG_ID = 0;

    private static final int NOTES_ACTION_MENU = 0;
    private static final int NEXT_ACTION_MENU = 1;

    
    TabHost mTabHost;
    ViewPager  mViewPager;
    TabsAdapter mTabsAdapter;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	
        menu.add(0,NOTES_ACTION_MENU,0, "Notes")
        .setIcon(R.drawable.notes)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 

        menu.add(0,NEXT_ACTION_MENU,0, "Next")
            .setIcon(R.drawable.next)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        
       return true; 
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        structureID = getIntent().getIntExtra("structureID", -1); //Get structureID otherwise -1  
        utilsHelper = new Utils(this);      
        structureCursor = utilsHelper.getStructureCursor(structureID);
        
        // Sets the title on the action bar to the be the name of the structure
        String structureTitle = " " + structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NAME)) + " Questionnaire";
        setTitle(structureTitle);   
        
        // Sets the view of the base activity
        setContentView(R.layout.fragment_tabs_pager);
        mTabHost = (TabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup();

        mViewPager = (ViewPager)findViewById(R.id.pager);

        mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

        // TABS are created and linked to various classses
//         "q"+Integer.toString(DEMOGRAPHICS_TAB) is a way of specifiy q0,q1,q2 TAGS that may be accessed. These tags are currently not used
        mTabsAdapter.addTab(mTabHost.newTabSpec("q"+Integer.toString(DEMOGRAPHICS_TAB)).setIndicator("Demographics"),
                FragmentDemographicsQuestionnaire.class, null);
        mTabsAdapter.addTab(mTabHost.newTabSpec("q"+Integer.toString(LAYOUT_TAB)).setIndicator("Layout"),
        		FragmentLayoutQuestionnaire.class, null);
        mTabsAdapter.addTab(mTabHost.newTabSpec("q"+Integer.toString(PRIMARY_SYSTEM_TAB)).setIndicator("Primary"),
        		FragmentPrimaryQuestionnaire.class, null);         
        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
        }
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case NOTES_ACTION_MENU:
            	showDialog(STRUCTURE_NOTE_DIALOG_ID);           	                       	            
                return true;  
            case NEXT_ACTION_MENU:
            	
                int tabID = mTabHost.getCurrentTab();
                
                // If its not the first time the application enters the Questionnaire tab, update the Formd data to the database
                    Fragment f = (Fragment) mViewPager.getAdapter().instantiateItem(mViewPager, tabID);
                	updateFormDataDB(f.getView() , tabID);
                	//updateFormDataDB(getItem(position).getView());            
            	
	            utilsHelper.startNextActivity(structureID, Questionnaire2.class);
                return true;                  
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("tab", mTabHost.getCurrentTabTag());
    }
    
    /**
     * This is a helper class that implements the management of tabs and all
     * details of connecting a ViewPager with associated TabHost.  It relies on a
     * trick.  Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show.  This is not sufficient for switching
     * between pages.  So instead we make the content part of the tab host
     * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
     * view to show as the tab content.  It listens to changes in tabs, and takes
     * care of switch to the correct paged in the ViewPager whenever the selected
     * tab changes.
     */
    
    
    public static class TabsAdapter extends FragmentPagerAdapter
            implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final TabHost mTabHost;
        private final ViewPager mViewPager;
        public int previousTabID = -1; // initialized to -1 when no tabs are selected
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {
            private final String tag;
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(String _tag, Class<?> _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        static class DummyTabFactory implements TabHost.TabContentFactory {
            private final Context mContext;

            public DummyTabFactory(Context context) {
                mContext = context;
            }

            @Override
            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }

        public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mTabHost = tabHost;
            mViewPager = pager;
            mTabHost.setOnTabChangedListener(this);
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
            tabSpec.setContent(new DummyTabFactory(mContext));
            String tag = tabSpec.getTag();

            TabInfo info = new TabInfo(tag, clss, args);
            mTabs.add(info);
            mTabHost.addTab(tabSpec);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        @Override
        // Positon is integer 0-N indiciating which tab
        // tabID is the lowercase name of the Tab
        public void onTabChanged(String tabId) {
            int position = mTabHost.getCurrentTab();
            
            // If its not the first time the application enters the Questionnaire tab, update the Formd data to the database
            if (previousTabID != -1) {
                Fragment f = (Fragment) mViewPager.getAdapter().instantiateItem(mViewPager, previousTabID);
            	Questionnaire.updateFormDataDB(f.getView(),previousTabID);
            	//updateFormDataDB(getItem(position).getView());
            }
                        
            previousTabID = position; // initialized to -1 when first enter into Questionnaire class
            mViewPager.setCurrentItem(position);

        }
        
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            // Unfortunately when TabHost changes the current tab, it kindly
            // also takes care of putting focus on it when not in touch mode.
            // The jerk.
            // This hack tries to prevent this from pulling focus out of our
            // ViewPager.
            TabWidget widget = mTabHost.getTabWidget();
            int oldFocusability = widget.getDescendantFocusability();
            widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            mTabHost.setCurrentTab(position);
            widget.setDescendantFocusability(oldFocusability);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    } // End of Tabs Adapter
    
 public static void updateFormDataDB(View v, int TabID){
    	
    	// Switches to the correct DB update information given the previous tab
   switch (TabID){
   
   		case DEMOGRAPHICS_TAB: 
   			
   		 // Demographic Questionnaire ==============================================================================
        	
        	// Declares the text input fields
   				EditText EditText_SurveyorName= (EditText) v.findViewById(R.id.Dem_editText_SurveyorName);
	        	EditText EditText_Entry_Descriptor = (EditText) v.findViewById(R.id.Dem_editText_EntryDescriptor);
	        	EditText EditText_Location = (EditText) v.findViewById(R.id.Dem_editText_Location);
	        	EditText EditText_FunctionUsageNote = (EditText) v.findViewById(R.id.Dem_editText_FunctionUsageNote);
	        	EditText EditText_TenantAddress = (EditText) v.findViewById(R.id.Dem_editText_TenantAddress);
	        	EditText EditText_TenantName = (EditText) v.findViewById(R.id.Dem_editText_TenantName);
	        	EditText EditText_TenantPhoneNumber = (EditText) v.findViewById(R.id.Dem_editText_TenantPhoneNumber);
	        	EditText EditText_OwnershipNote = (EditText) v.findViewById(R.id.Dem_editText_OwnershipNote);
	        	EditText EditText_YearBuilt = (EditText) v.findViewById(R.id.Dem_editText_YearBuilt);
	        	EditText EditText_ConstructionTime = (EditText) v.findViewById(R.id.Dem_editText_ConstructionTime);
	        	EditText EditText_BulderNote = (EditText) v.findViewById(R.id.Dem_editText_BuilderNote);
	        	EditText EditText_NumberOfAdults = (EditText) v.findViewById(R.id.Dem_editText_NumberOfAdults);
	        	EditText EditText_NumberOfChildren = (EditText) v.findViewById(R.id.Dem_editText_NumberOfChildren);
	        	
	        	// Declares the checkbox input fields
	        	CheckBox CheckBox_FunctionUsage_Residence = (CheckBox) v.findViewById(R.id.Dem_checkBox_FunctionUsageResidence);
	        	CheckBox CheckBox_FunctionUsage_Mixed = (CheckBox) v.findViewById(R.id.Dem_checkBox_FunctionUsageMixed);
	        	CheckBox CheckBox_FunctionUsage_Single = (CheckBox) v.findViewById(R.id.Dem_checkBox_FunctionUsageSingle);
	        	CheckBox CheckBox_FunctionUsage_Multiple = (CheckBox) v.findViewById(R.id.Dem_checkBox_FunctionUsageMultiple);
	        	CheckBox CheckBox_FunctionUsage_Other= (CheckBox) v.findViewById(R.id.Dem_checkBox_FunctionUsageOther);
	        	
	        	// Declares Spinner input fields
        	Spinner Spinner_Ownership = (Spinner) v.findViewById(R.id.Dem_spinner_Ownership);
	        	Spinner Spinner_Builder = (Spinner) v.findViewById(R.id.Dem_spinner_Builder);

            // Extracts the string value from the Edit text fields
  	  		String surveyorName = EditText_SurveyorName.getText().toString();
  	  		String entryDescriptor = EditText_Entry_Descriptor.getText().toString();
  	  		String location = EditText_Location.getText().toString();
  	  		String functionUsageNote = EditText_FunctionUsageNote.getText().toString();
  	  		String tenantAddress = EditText_TenantAddress.getText().toString();
  	  		String tenantName = EditText_TenantName.getText().toString();
  	  		String tenantPhoneNumber = EditText_TenantPhoneNumber.getText().toString();
  	  		String ownershipNote = EditText_OwnershipNote.getText().toString();
  	  		String yearbuilt = EditText_YearBuilt.getText().toString();
  	  		String constructionTime = EditText_ConstructionTime.getText().toString();
  	  		String builderNote= EditText_BulderNote.getText().toString();
  	  		String numberOfAdults = EditText_NumberOfAdults.getText().toString();
  	  		String numberOfChildren = EditText_NumberOfChildren.getText().toString();
  	  		
  	  		// Extracts the value from the check boxes
			String functionUsageResidence = boolToString(CheckBox_FunctionUsage_Residence.isChecked());
			String functionUsageMixed= boolToString(CheckBox_FunctionUsage_Mixed.isChecked());
			String functionUsageSingle= boolToString(CheckBox_FunctionUsage_Single.isChecked());
			String functionUsageMultiple= boolToString(CheckBox_FunctionUsage_Multiple.isChecked());
			String functionUsageOther= boolToString(CheckBox_FunctionUsage_Other.isChecked());
	        	
            // Extracts the string value from the Spinners
  	  		String ownership = Spinner_Ownership.getSelectedItem().toString();
  	  		String builder = Spinner_Builder.getSelectedItem().toString();
  	  		
  	  		// Checks Progress of overall app
  			String status = Questionnaire.structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_STATUS));
  			
  			// If the Status is New, update it to In Progress, if it is completed, or uploaded nothing should change
  			if (status.equals("New")){
  				status = "In Progress";
  			}

  	  		String[][] databaseUpdatesDemographics = {
        			{SqlHelper.COLUMN_SURVEYOR_NAME, surveyorName},
        			{SqlHelper.COLUMN_STRUCTURE_ENTRY_DESCRIPTOR,entryDescriptor},
    				{SqlHelper.COLUMN_STRUCTURE_LOCATION,location},
    				{SqlHelper.COLUMN_STRUCTURE_STATUS,status},
    				{SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_RESIDENCE,functionUsageResidence},
    				{SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_MIXED,functionUsageMixed},
    				{SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_SINGLE,functionUsageSingle},
    				{SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_MULTIPLE,functionUsageMultiple},
    				{SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_OTHER,functionUsageOther},
					{SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_NOTE,functionUsageNote},
					{SqlHelper.COLUMN_TENANT_ADDRESS,tenantAddress},
					{SqlHelper.COLUMN_TENANT_NAME,tenantName},
					{SqlHelper.COLUMN_TENANT_PHONE_NUMBER,tenantPhoneNumber},
					{SqlHelper.COLUMN_STRUCTURE_OWNERSHIP_STATUS,ownership}, 
					{SqlHelper.COLUMN_STRUCTURE_OWNERSHIP_STATUS_NOTE,ownershipNote}, 
					{SqlHelper.COLUMN_STRUCTURE_YEAR_BUILT,yearbuilt},
					{SqlHelper.COLUMN_STRUCTURE_CONSTRUCTION_DURATION,constructionTime},
					{SqlHelper.COLUMN_STRUCTURE_BUILDER,builder},
					{SqlHelper.COLUMN_STRUCTURE_BUILDER_NOTE,builderNote},
					{SqlHelper.COLUMN_STRUCTURE_NUMBER_OF_ADULTS,numberOfAdults},
					{SqlHelper.COLUMN_STRUCTURE_NUMBER_OF_CHILDREN,numberOfChildren}
					}; 
            
            // Updates the entries in the database
            updateStructureDB(databaseUpdatesDemographics);
            break;
      // 	===============================================================================================  
   			
   		case LAYOUT_TAB:
   			
		 // Layout Questionnaire ==============================================================================
        	
        	// Declares the text input fields
	        	EditText EditText_NumberOfRooms = (EditText) v.findViewById(R.id.Layout_editText_NumberOfRooms);
	        	EditText EditText_PlanDimensionsWidth = (EditText) v.findViewById(R.id.Layout_editText_PlanDimensionsWidth);
	        	EditText EditText_PlanDimensionsDepth = (EditText) v.findViewById(R.id.Layout_editText_PlanDimensionsDepth);
	        	
	        	// Declares Spinner input fields
  			Spinner Spinner_nLevels = (Spinner) v.findViewById(R.id.Layout_spinner_NumberOfLevels);

            // Extracts the string value from the Edit text fields
  	  		String nRooms = EditText_NumberOfRooms.getText().toString();
  	  		String planDimensionsWidth = EditText_PlanDimensionsWidth.getText().toString();
  	  		String planDimensionsDepth = EditText_PlanDimensionsDepth.getText().toString();
	        	
            // Extracts the string value from the Spinners
  	  		String nLevels = Spinner_nLevels.getSelectedItem().toString();

  	  		String[][] databaseUpdatesLayout = {
        			{SqlHelper.COLUMN_STRUCTURE_NUMBER_OF_LEVELS,nLevels},
    				{SqlHelper.COLUMN_STRUCTURE_NUMBER_OF_ROOMS,nRooms},
    				{SqlHelper.COLUMN_STRUCTURE_PLAN_DIMENSIONS_WIDTH,planDimensionsWidth},
					{SqlHelper.COLUMN_STRUCTURE_PLAN_DIMENSIONS_DEPTH,planDimensionsDepth}
					}; 
            
            // Updates the entries in the database
            updateStructureDB(databaseUpdatesLayout);
            break;
      // 	===============================================================================================  
            
   		case PRIMARY_SYSTEM_TAB:
			
	 // Primary System Questionnaire ==============================================================================
    	
	    	// Declares the text input fields
			EditText EditText_SystemConditionNote = (EditText) v.findViewById(R.id.Primary_editText_SystemConditionNote);
			EditText EditText_ExteriorWallMaterialNote = (EditText) v.findViewById(R.id.Primary_editText_ExteriorWallMaterialNote);    
			EditText EditText_ExteriorWallConditionNote = (EditText) v.findViewById(R.id.Primary_editText_ExteriorWallConditionNote);
			EditText EditText_ExteriorWallThickness = (EditText) v.findViewById(R.id.Primary_editText_WallThickness);    
			EditText EditText_StructuralSystemNote = (EditText) v.findViewById(R.id.Primary_editText_StructuralSystemNote); 
			EditText EditText_ColumnConstructionMaterialNote = (EditText) v.findViewById(R.id.Primary_editText_ColumnConstructionMaterialNote);    
			EditText EditText_FullColumnWidth = (EditText) v.findViewById(R.id.Primary_editText_FullColumnWidth);    
			EditText EditText_FullColumnDepth = (EditText) v.findViewById(R.id.Primary_editText_FullColumnDepth);    
			EditText EditText_ColumnRebarCageWidth = (EditText) v.findViewById(R.id.Primary_editText_ColumnRebarCageWidth);    
			EditText EditText_ColumnRebarCageDepth = (EditText) v.findViewById(R.id.Primary_editText_ColumnRebarCageDepth);    
			EditText EditText_ColumnLongitudinaBarsNumber = (EditText) v.findViewById(R.id.Primary_editText_ColumnLongitudinaBarsNumber);    
			EditText EditText_ColumnMinimumTransverseSpacing = (EditText) v.findViewById(R.id.Primary_editText_ColumnMinimumTransverseSpacing);    
			EditText EditText_BeamConstructionMaterialNote = (EditText) v.findViewById(R.id.Primary_editText_BeamConstructionMaterialNote);    
			EditText EditText_FullBeamWidth = (EditText) v.findViewById(R.id.Primary_editText_FullBeamWidth); 
			EditText EditText_FullBeamDepth = (EditText) v.findViewById(R.id.Primary_editText_FullBeamDepth);    
			EditText EditText_BeamRebarCageWidth = (EditText) v.findViewById(R.id.Primary_editText_BeamRebarCageWidth);    
			EditText EditText_BeamRebarCageDepth = (EditText) v.findViewById(R.id.Primary_editText_BeamRebarCageDepth);    
			EditText EditText_BeamLongitudinaBarsNumber = (EditText) v.findViewById(R.id.Primary_editText_BeamLongitudinaBarsNumber);    
			EditText EditText_BeamMinimumTransverseSpacing = (EditText) v.findViewById(R.id.Primary_editText_BeamMinimumTransverseSpacing);
		    
		    // Declares the checkbox input fields
			CheckBox CheckBox_ExteriorWallMaterial_Masonry = (CheckBox) v.findViewById(R.id.Primary_checkBox_ExteriorWallMaterial_Masonry);
			CheckBox CheckBox_ExteriorWallMaterial_Stone = (CheckBox) v.findViewById(R.id.Primary_checkBox_ExteriorWallMaterial_Stone);
			CheckBox CheckBox_ExteriorWallMaterial_Earth = (CheckBox) v.findViewById(R.id.Primary_checkBox_ExteriorWallMaterial_Earth);
			CheckBox CheckBox_ExteriorWallMaterial_Wood = (CheckBox) v.findViewById(R.id.Primary_checkBox_ExteriorWallMaterial_Wood);
			CheckBox CheckBox_ExteriorWallMaterial_Metal = (CheckBox) v.findViewById(R.id.Primary_checkBox_ExteriorWallMaterial_Metal);
			CheckBox CheckBox_ExteriorWallMaterial_Other = (CheckBox) v.findViewById(R.id.Primary_checkBox_ExteriorWallMaterial_Other);
		    CheckBox CheckBox_WallReinforcement = (CheckBox) v.findViewById(R.id.Primary_checkBox_WallReinforcement);
		    CheckBox CheckBox_ColumnsPresent = (CheckBox) v.findViewById(R.id.Primary_checkBox_ColumnsPresent);
		    CheckBox CheckBox_RingBeam = (CheckBox) v.findViewById(R.id.Primary_checkBox_RingBeam);
		    CheckBox CheckBox_Concrete_Column = (CheckBox) v.findViewById(R.id.Primary_checkBox_Concrete_Column);
		    CheckBox CheckBox_Metal_Column = (CheckBox) v.findViewById(R.id.Primary_checkBox_Metal_Column);
		    CheckBox CheckBox_Wood_Column = (CheckBox) v.findViewById(R.id.Primary_checkBox_Wood_Column);
		    CheckBox CheckBox_Bamboo_Column	 = (CheckBox) v.findViewById(R.id.Primary_checkBox_Bamboo_Column);
	   		CheckBox CheckBox_Other_Column = (CheckBox) v.findViewById(R.id.Primary_checkBox_Other_Column);
	   		CheckBox CheckBox_Concrete_Beam= (CheckBox) v.findViewById(R.id.Primary_checkBox_Concrete_Beam);
	   		CheckBox CheckBox_Metal_Beam= (CheckBox) v.findViewById(R.id.Primary_checkBox_Metal_Beam);
	   		CheckBox CheckBox_Wood_Beam= (CheckBox) v.findViewById(R.id.Primary_checkBox_Wood_Beam);
	   		CheckBox CheckBox_Bamboo_Beam= (CheckBox) v.findViewById(R.id.Primary_checkBox_Bamboo_Beam);
	   		CheckBox CheckBox_Other_Beam= (CheckBox) v.findViewById(R.id.Primary_checkBox_Other_Beam);
        	
        	// Declares Spinner input fields
			Spinner Spinner_SystemCondition = (Spinner) v.findViewById(R.id.Primmary_spinner_SystemCondition);
			Spinner Spinner_ExteriorWallCondition = (Spinner) v.findViewById(R.id.Primmary_spinner_ExteriorWallCondition);
			Spinner Spinner_StructuralSystem = (Spinner) v.findViewById(R.id.Primmary_spinner_StructuralSystem);
			Spinner Spinner_ColumnLongitudinaBarsSize = (Spinner) v.findViewById(R.id.Primmary_spinner_ColumnLongitudinaBarsSize);
			Spinner Spinner_ColumnBarTexture = (Spinner) v.findViewById(R.id.Primmary_spinner_ColumnBarTexture);
			Spinner Spinner_ColumnHookDetail = (Spinner) v.findViewById(R.id.Primmary_spinner_ColumnHookDetail);
			Spinner Spinner_BeamLongitudinaBarsSize = (Spinner) v.findViewById(R.id.Primmary_spinner_BeamLongitudinaBarsSize);
			Spinner Spinner_BeamBarTexture = (Spinner) v.findViewById(R.id.Primmary_spinner_BeamBarTexture);
			Spinner Spinner_BeamHookDetail = (Spinner) v.findViewById(R.id.Primmary_spinner_BeamHookDetail);

        // Extracts the string value from the Edit text fields
  	  	String systemConditionNote = EditText_SystemConditionNote.getText().toString();
		String exteriorWallMaterialNote = EditText_ExteriorWallMaterialNote.getText().toString();
		String exteriorWallConditionNote = EditText_ExteriorWallConditionNote.getText().toString();
		String exteriorWallThickness = EditText_ExteriorWallThickness.getText().toString();
		String structuralSystemNote = EditText_StructuralSystemNote.getText().toString();
		String columnConstructionMaterialNote = EditText_ColumnConstructionMaterialNote.getText().toString();
		String fullColumnWidth = EditText_FullColumnWidth.getText().toString();
		String fullColumnDepth = EditText_FullColumnDepth.getText().toString();
		String columnRebarCageWidth = EditText_ColumnRebarCageWidth.getText().toString();
		String columnRebarCageDepth= EditText_ColumnRebarCageDepth.getText().toString();
		String columnLongitudinalBarNumber =  EditText_ColumnLongitudinaBarsNumber.getText().toString();
		String columnMinimumTransverseSpacing =  EditText_ColumnMinimumTransverseSpacing.getText().toString();;
		String beamConstructionMaterialNote = EditText_BeamConstructionMaterialNote.getText().toString();
		String fullBeamWidth =  EditText_FullBeamWidth.getText().toString();
		String fullBeamDepth =  EditText_FullBeamDepth.getText().toString();
		String beamRebarCageWidth =  EditText_BeamRebarCageWidth.getText().toString();
		String beamRebarCageDepth =  EditText_BeamRebarCageDepth.getText().toString();
		String beamLongitudinalBarsNumber =  EditText_BeamLongitudinaBarsNumber.getText().toString();
		String beamMinimumTransverseSpacing =  EditText_BeamMinimumTransverseSpacing.getText().toString();
	  		
	  		// Extracts the value from the check boxes
		String exteriorMasonry = boolToString(CheckBox_ExteriorWallMaterial_Masonry.isChecked());
		String exteriorStone= boolToString(CheckBox_ExteriorWallMaterial_Stone.isChecked());
		String exteriorEarth = boolToString(CheckBox_ExteriorWallMaterial_Earth .isChecked());
		String exteriorWood = boolToString(CheckBox_ExteriorWallMaterial_Wood.isChecked());
		String exteriorMetal = boolToString(CheckBox_ExteriorWallMaterial_Metal.isChecked());
		String exteriorOther = boolToString(CheckBox_ExteriorWallMaterial_Other.isChecked());
		String wallReinforcement = boolToString(CheckBox_WallReinforcement.isChecked());
		String columnsPresent = boolToString(CheckBox_ColumnsPresent.isChecked());
		String ringBeam = boolToString(CheckBox_RingBeam.isChecked());
		String concreteColumn = boolToString(CheckBox_Concrete_Column.isChecked());
		String  metalColumn = boolToString(CheckBox_Metal_Column.isChecked());
		String  woodColumn = boolToString(CheckBox_Wood_Column.isChecked());
		String  bambooColumn = boolToString(CheckBox_Bamboo_Column.isChecked());
		String  otherColumn = boolToString(CheckBox_Other_Column.isChecked());
		String  concreteBeam = boolToString(CheckBox_Concrete_Beam.isChecked());
		String  metalBeam= boolToString(CheckBox_Metal_Beam.isChecked());
		String  woodBeam= boolToString(CheckBox_Wood_Beam.isChecked());
		String  bambooBeam= boolToString(CheckBox_Bamboo_Beam.isChecked());
		String  otherBeam= boolToString(CheckBox_Other_Beam.isChecked());
				
        // Extracts the string value from the Spinners
//	  		String nLevels = Spinner_nLevels.getSelectedItem().toString();
		String systemCondition = Spinner_SystemCondition.getSelectedItem().toString();
		String exteriorWallCondition = Spinner_ExteriorWallCondition.getSelectedItem().toString();
		String structralSystem = Spinner_StructuralSystem.getSelectedItem().toString();
		String columnLongitudinalBarsSize = Spinner_ColumnLongitudinaBarsSize.getSelectedItem().toString();
		String columnBarTexture = Spinner_ColumnBarTexture.getSelectedItem().toString();
		String columnHookDetail = Spinner_ColumnHookDetail.getSelectedItem().toString();
		String beamLongitudinalBarsSize = Spinner_BeamLongitudinaBarsSize.getSelectedItem().toString();
		String beamBarTexture = Spinner_BeamBarTexture.getSelectedItem().toString();
		String beamHookDetails = Spinner_BeamHookDetail.getSelectedItem().toString();			

	  		String[][] databaseUpdatesPrimary= {
	  			{SqlHelper.COLUMN_STRUCTURE_EXTERIOR_WALL_MATERIAL_MASONRY,exteriorMasonry}, 
	  			{SqlHelper.COLUMN_STRUCTURE_EXTERIOR_WALL_MATERIAL_STONE,exteriorStone}, 
	  			{SqlHelper.COLUMN_STRUCTURE_EXTERIOR_WALL_MATERIAL_EARTH,exteriorEarth}, 
	  			{SqlHelper.COLUMN_STRUCTURE_EXTERIOR_WALL_MATERIAL_WOOD,exteriorWood}, 
	  			{SqlHelper.COLUMN_STRUCTURE_EXTERIOR_WALL_MATERIAL_METAL,exteriorMetal}, 
	  			{SqlHelper.COLUMN_STRUCTURE_EXTERIOR_WALL_MATERIAL_OTHER,exteriorOther}, 
	  			{SqlHelper.COLUMN_STRUCTURE_EXTERIOR_WALL_MATERIAL_NOTE,exteriorWallMaterialNote},
	  			{SqlHelper.COLUMN_STRUCTURE_PRIMARY_SYSTEM_CONDITION,systemCondition},
	  			{SqlHelper.COLUMN_STRUCTURE_PRIMARY_SYSTEM_CONDITION_NOTE,systemConditionNote}, 	  	  			
	  			{SqlHelper.COLUMN_STRUCTURE_EXTERIOR_WALL_CONDITION,exteriorWallCondition}, 
	  			{SqlHelper.COLUMN_STRUCTURE_EXTERIOR_WALL_CONDITION_NOTE,exteriorWallConditionNote},
	  			{SqlHelper.COLUMN_STRUCTURE_EXTERIOR_WALL_THICKNESS,exteriorWallThickness}, 
	  			{SqlHelper.COLUMN_STRUCTURE_STRUCTURAL_SYSTEM,structralSystem}, 
	  			{SqlHelper.COLUMN_STRUCTURE_STRUCTURAL_SYSTEM_NOTE,structuralSystemNote},
	  			{SqlHelper.COLUMN_STRUCTURE_LOAD_BEARING_WALL_REINFORCEMENT,wallReinforcement}, 
	  			{SqlHelper.COLUMN_STRUCTURE_LOAD_BEARING_WALL_COLUMNS_PRESENT,columnsPresent}, 
	  			{SqlHelper.COLUMN_STRUCTURE_LOAD_BEARING_WALL_RING_BEAM,ringBeam}, 
		  	    		// Column Details
	  			{SqlHelper.COLUMN_STRUCTURE_COLUMN_CONSTRUCTION_MATERIAL_CONCRETE,concreteColumn},
	  			{SqlHelper.COLUMN_STRUCTURE_COLUMN_CONSTRUCTION_MATERIAL_METAL,metalColumn}, 
	  			{SqlHelper.COLUMN_STRUCTURE_COLUMN_CONSTRUCTION_MATERIAL_WOOD,woodColumn}, 
	  			{SqlHelper.COLUMN_STRUCTURE_COLUMN_CONSTRUCTION_MATERIAL_BAMBOO,bambooColumn},
	  			{SqlHelper.COLUMN_STRUCTURE_COLUMN_CONSTRUCTION_MATERIAL_OTHER,otherColumn}, 
	  			{SqlHelper.COLUMN_STRUCTURE_COLUMN_CONSTRUCTION_MATERIAL_NOTE,columnConstructionMaterialNote},
	  			{SqlHelper.COLUMN_STRUCTURE_FULL_COLUMN_WIDTH,fullColumnWidth}, 
	  			{SqlHelper.COLUMN_STRUCTURE_FULL_COLUMN_DEPTH,fullColumnDepth}, 
	  			{SqlHelper.COLUMN_STRUCTURE_COLUMN_REBAR_CAGE_WIDTH,columnRebarCageWidth},
	  	    	{SqlHelper.COLUMN_STRUCTURE_COLUMN_REBAR_CAGE_DEPTH,columnRebarCageDepth},
	  	    	{SqlHelper.COLUMN_STRUCTURE_COLUMN_REINFORCEMENT_NUMBER_OF_LONGITUDINAL_BARS,columnLongitudinalBarNumber}, 
	  			{SqlHelper.COLUMN_STRUCTURE_COLUMN_REINFORCEMENT_LONGITUDINAL_BAR_SIZE,columnLongitudinalBarsSize},
  		    	{SqlHelper.COLUMN_STRUCTURE_COLUMN_REINFORCEMENT_BAR_TEXTURE,columnBarTexture}, 
	  			{SqlHelper.COLUMN_STRUCTURE_COLUMN_REINFORCEMENT_MINIMUM_TRANSVERSE_SPACING,columnMinimumTransverseSpacing},
	  			{SqlHelper.COLUMN_STRUCTURE_COLUMN_REINFORCEMENT_HOOK_DETAIL,columnHookDetail}, 
		  	    		// Beam Details
				{SqlHelper.COLUMN_STRUCTURE_BEAM_CONSTRUCTION_MATERIAL_CONCRETE,concreteBeam},
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_CONSTRUCTION_MATERIAL_METAL,metalBeam}, 
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_CONSTRUCTION_MATERIAL_WOOD,woodBeam}, 
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_CONSTRUCTION_MATERIAL_BAMBOO,bambooBeam}, 
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_CONSTRUCTION_MATERIAL_OTHER,otherBeam}, 
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_CONSTRUCTION_MATERIAL_NOTE,beamConstructionMaterialNote},
	  			{SqlHelper.COLUMN_STRUCTURE_FULL_BEAM_WIDTH,fullBeamWidth}, 
	  			{SqlHelper.COLUMN_STRUCTURE_FULL_BEAM_DEPTH,fullBeamDepth}, 
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_REBAR_CAGE_WIDTH,beamRebarCageWidth}, 
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_REBAR_CAGE_DEPTH,beamRebarCageDepth}, 
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_REINFORCEMENT_NUMBER_OF_LONGITUDINAL_BARS,beamLongitudinalBarsNumber}, 
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_REINFORCEMENT_LONGITUDINAL_BAR_SIZE,beamLongitudinalBarsSize}, 
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_REINFORCEMENT_BAR_TEXTURE,beamBarTexture},
	  			{SqlHelper.COLUMN_STRUCTURE_BEAM_REINFORCEMENT_MINIMUM_TRANSVERSE_SPACING,beamMinimumTransverseSpacing},
				{SqlHelper.COLUMN_STRUCTURE_BEAM_REINFORCEMENT_HOOK_DETAIL,beamHookDetails}    
	  			};
	  		
        // Updates the entries in the database
        updateStructureDB(databaseUpdatesPrimary);
        break;
  // 	===============================================================================================  
   			
   		default: // Update form tab ID was not found
   			// current does nothing
   			break;
   		}
       
    }

    public static String boolToString(Boolean b) {
    	  if (b)
    	    return "1";
    	  if (!b)
    	    return "0";
    	  throw new IllegalArgumentException(b+" is not a bool. Only 1 and 0 are.");
    }
      
      public static void updateStructureDB(String[][] databaseUpdates){
          // Push the changes to the database
          utilsHelper.openDatabase();
          utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID );
          utilsHelper.closeDatabase();
      }
    
    @Override
    protected Dialog onCreateDialog(int id) {
		
            switch (id) {

            case STRUCTURE_NOTE_DIALOG_ID:
            	AlertDialog.Builder builder = new AlertDialog.Builder(this);
                
                // Inflates the custom xml file layout create_structure_dialog.xml
                LayoutInflater inflater = this.getLayoutInflater();    
                View  dialogView  =  inflater.inflate(R.layout.structure_notes_dialog,null);
                builder.setView(dialogView);
                
                builder.setTitle(R.string.structure_notes_dialog_title);
                //builder2.setIcon(R.drawable.icon);    
                
                final EditText EditText_structureNotes = (EditText) dialogView.findViewById(R.id.structureNotes);     
                
                builder.setPositiveButton(R.string.save,
                		          
                                new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            
                                        	// Defines strings input in by the user
                                            String structureNotes = EditText_structureNotes.getText().toString();
                                        	
                                            // Updates the user-defined structure to  the database
                                            //structureID = adapter.getCursor().getInt(adapter.getCursor().getColumnIndex(SqlHelper.COLUMN_ID));
                                            String[][] databaseUpdates = {
                                                    {SqlHelper.COLUMN_STRUCTURE_NOTES, structureNotes} 
                                                    };

                                            utilsHelper.openDatabase();                	
                                            utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID );
                                            structureCursor = utilsHelper.getStructureCursor(structureID);
                                           // utilsHelper.closeDatabase();                	
                                            
                                            return;
                                        }
                                });

                builder.setNegativeButton(android.R.string.cancel,
                                new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {                                                   
                                                return;
                                        }
                                });    
                
                Dialog structureDialogEdit = builder.create();

                return structureDialogEdit;
        }
            
            return null;
                                                  
    }
    
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {   	
 
        switch (id) { 
            case STRUCTURE_NOTE_DIALOG_ID:
            	
            	final EditText structureNotes = (EditText) dialog.findViewById(R.id.structureNotes);     
            	
        		//Clear the EditText fields
        		String oldNotes= structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTES));
        		
        		structureNotes.setText(oldNotes); 
        		structureNotes.requestFocus();
                break;            	
                
            default:
            	Log.d(LAYOUT_INFLATER_SERVICE, "Wrong Structure DIALOG ID");
            	break;
        }
    }
}
